package com.poi.qianmi.fetch.demo2.handle;

import com.poi.qianmi.conver.UserConver;
import com.poi.qianmi.model.User;
import org.apache.poi.xssf.usermodel.XSSFComment;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname DefaultSheetHandler
 * @Description TODO
 * @Date 2019/9/19 8:03 下午
 * @Created by xiaocai
 */
public class DefaultSheetHandler implements ISheetContentHandler {

    //用户信息
    private List<User> userList;
    //存放每组数据
    private ArrayList<String> fristRow = new ArrayList<String>();

    // 读取行信息
    private String[] readRow;
    private int columsLength;

    public void init(List<User> userList) {
        this.userList = userList;
    }

    public void startRow(int i) {
        if (i != 0) {
            readRow = new String[columsLength];
        }
    }

    public void endRow(int i) {
        //将Excel第一行表头的列数当做数组的长度，要保证后续的行的列数不能超过这个长度，这是个约定。
        if (i == 0) {
            columsLength = fristRow.size();
            readRow = fristRow.toArray(new String[fristRow.size()]);
        } else {
            readRow = fristRow.toArray(new String[columsLength]);
        }
        userList.add(UserConver.converterTosheet(readRow));

        readRow = null;
        fristRow.clear();
    }

    public void cell(String s, String s1, XSSFComment xssfComment) {
        int index = getCellIndex(s);//转换A1,B1,C1等表格位置为真实索引位置
        try {
            fristRow.set(index, s1);
        } catch (IndexOutOfBoundsException e) {
            int size = fristRow.size();
            for (int i = index - size + 1; i > 0; i--) {
                fristRow.add(null);
            }
            fristRow.set(index, s1);
        }

    }

    public void headerFooter(String s, boolean b, String s1) {

    }

    /**
     * 转换表格引用为列编号
     *
     * @param cellReference 列引用
     * @return 表格列位置，从0开始算
     */
    public int getCellIndex(String cellReference) {
        String ref = cellReference.replaceAll("\\d+", "");
        int num = 0;
        int result = 0;
        for (int i = 0; i < ref.length(); i++) {
            char ch = cellReference.charAt(ref.length() - i - 1);
            num =(ch - 'A' + 1);
            num *= Math.pow(26, i);
            result += num;
        }
        return result - 1;
    }
}
